package Demo3_12;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User：Lenovo
 * Date:2025-03-12
 * Time:16:50
 */
public class BinarySearchTree {
    static class TreeNode{
        public int val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(int val){
            this.val=val;
        }
    }
    //当前搜索树的根节点
    public TreeNode root=null;
    public TreeNode  search(int val){
      TreeNode cur=root;
     while(cur!=null){
         if(cur.val<val){
             cur=cur.right;
         }else if(cur.val>val){
             cur=cur.left;
         }
         else{
             return cur;
         }
      }
     return null;
    }
    public void insert(int val){
        TreeNode newNode=new TreeNode(val);
        if(root==null){
            root=newNode;
            return;
        }
        TreeNode cur=root;
        TreeNode parent=null;
        while(cur!=null){
            if(cur.val<val){
                parent=cur;
                cur=cur.right;
            }else if(cur.val>val){
                parent =cur;
                cur=cur.left;
            }else{
                return ;
            }
        }
        if(parent.val<val){
            parent.right=newNode;
        } else{
            parent.left=newNode;
        }
    }
}
